package sunlight.ws.axis2.clients;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;

public class ResourceUpdatingClient {
	
	public static EndpointReference targetEPR = 
        new EndpointReference("http://localhost:8080/axis2/services/ResourceUpdatingService");
	
	private String lastUpdateTime;
	
	private ServiceClient sender;
	private Options options;
	
	private String resourceID;
	
	private OMElement notifyUpdatePayload;
	private OMElement getLastUpdatePayload;
	
	public ResourceUpdatingClient(String resourceID) throws AxisFault{
		super();
		 
		options = new Options();
		options.setTo(targetEPR);
		options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
			
		sender = new ServiceClient();
		sender.setOptions(options);
		
		this.resourceID = resourceID;
		
		//------~ Inititlizeaza metodele ~------//
		notifyUpdatePayload   = notifyUpdatePayload(this.resourceID);
		getLastUpdatePayload  = getLastUpdatePayload(this.resourceID);
	}

	
	public void notifyUpdate() throws AxisFault{
		sender.fireAndForget(notifyUpdatePayload);
	}
	
	public String getLastUpdate() throws AxisFault{		
		OMElement result = sender.sendReceive(getLastUpdatePayload);
		String response  = result.getFirstElement().getText();
		
		return response;
	}
	
	public void closeClient() throws AxisFault{
		this.sender.cleanup();
		this.sender.cleanupTransport();
	}
	
	public boolean hasChanged() throws AxisFault{
		String lastUpdate = getLastUpdate();
		
		if(this.lastUpdateTime.equals(lastUpdate)){
			return false;
		}
		
		this.lastUpdateTime = lastUpdate;
		
		return true;
	}
	
	
	public static OMElement notifyUpdatePayload(String rname) {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace("http://adrian.sunlight.ws.axis2/xsd", "tns");

        OMElement method = fac.createOMElement("notifyUpdate", omNs);
        
        OMElement value = fac.createOMElement("resource", omNs);
        value.addChild(fac.createOMText(value, rname));
        method.addChild(value);
        
        return method;
    }
    
    public static OMElement getLastUpdatePayload(String rname) {
    	 OMFactory fac = OMAbstractFactory.getOMFactory();
	     OMNamespace omNs = fac.createOMNamespace("http://adrian.sunlight.ws.axis2/xsd", "tns");

	     OMElement method = fac.createOMElement("getLastUpdate", omNs);

	     OMElement value = fac.createOMElement("resource", omNs);
	     value.addChild(fac.createOMText(value, rname));
	     method.addChild(value);
	        
	     return method;
    }
}
